package com.sunxueqi.framework.security.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.sunxueqi.framework.security.LoginUser;
import com.sunxueqi.project.system.service.UserService;
import com.sunxueqi.project.system.vo.User;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService{

	@Autowired
	private UserService userService;
	
	@Autowired
	private PermissionService permissionService;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userService.selectUserByUsername(username);
		if(ObjectUtil.isNull(user)) {
			log.info("用户：{}不存在", username);
			throw new UsernameNotFoundException("用户【" + username +"】不存在");
		} else if (user.getDeleteTime() !=null) {
			log.info("用户：{}已被删除", username);
			throw new UsernameNotFoundException("用户【" + username +"】已被删除");
		} 
		return createLoginUser(user);
	}

	public UserDetails createLoginUser(User user) {
		return new LoginUser(user, permissionService.getMenuPermission(user));
	}
}
